<?php
/**
 * 图片上传
 * @return
 * @author yuncran@126.com
 */

namespace app\api\controller;

use app\BaseController;
use app\enterprise\model\File as FileModel;
use app\enterprise\model\Message;
use app\enterprise\model\User;
use app\model\AttachmentModel;
use think\facade\Filesystem;
use think\facade\Request;
use think\File;

class Upload extends BaseController
{


    protected $disk = '';
    protected $url = '';

    public function __construct()
    {
        parent::__construct(app());
        $this->disk = env('filesystem.driver', 'local');
        $this->url = getDiskUrl() . '/';

    }


    /**
     * 上传图片
     * @return \think\response\Json
     * @author yuncran@126.com
     */
    public function uploadImage()
    {
        $param = request::param();
        try {
            $file = request()->file('file');
            $info = $this->upload($param, $file, 'image/' . date('Y-m-d') . '/');
            $data = [
                'domain' => $this->url,
                'url' => '/uploads' . $info['src'],
                'path' => realpath(FAST . '/../backend/public/') . "/" . date('Ymd') . "/",
                'pathUrl' => $this->url . "/backend/public" . $info['src'],
            ];
            $try = AttachmentModel::where('sha1',$info['sha1'])->find();
            if(empty($try)){
                //添加附件中
                AttachmentModel::create([
                    'category' => 'category1', 'admin_id' => '1', 'user_id' => $this->uid,
                    'url' => $data['url'],
                    'imagewidth' => '', // 宽度
                    'imageheight' => '', //高度
                    'imageframes' => '', //图片帧数
                    'imagetype' => $info['ext'], //图片类型
                    'filename' => $info['name'], //文件名称
                    'filesize' => $info['size'], //文件大小
                    'mimetype' => $info['file_type'], //mime类型
                    'createtime' => time(), 'updatetime' => time(), 'uploadtime' => time(), 'storage' => 'local', 'sha1' => sha1($info['md5']), //文件 sha1编码
                ]);
            }
            return echoShutDown(lang('file.uploadOk'), '200', $data);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }

    /**
     * 文件上传
     */
    public function upload($data, $path, $prefix = "", $fileObj = true)
    {
        $message = $data['message'] ?? '';
        if ($message) {
            $message = json_decode($message, true);
        }
        $uid = request()->userInfo['user_id'] ?? 1;
        if ($fileObj) {
            $filePath = $path;
        } else {
            $filePath = new File($path);
        }
        $info = $this->getFileInfo($filePath, $path, $fileObj);

        if ($info['ext'] == '' && $message) {
            $pathInfo = pathinfo($message['fileName'] ?? '');
            $info['ext'] = $pathInfo['extension'];
            $info['name'] = $message['fileName'] ?? '';
        }
        $conf = \app\manage\model\Config::where(['name' => 'fileUpload'])->value('value');
        if ($conf['size'] * 1024 * 1024 < $info['size']) {
            return echoShutDown(lang('file.uploadLimit', ['size' => $conf['size']]));
        }
        // 兼容uniapp文件上传
        if ($info['ext'] == '' && isset($data['ext'])) {
            $info['ext'] = $data['ext'];
        }
        $info['ext'] = strtolower($info['ext']);
        if (!in_array($info['ext'], $conf['fileExt'])) {
            return echoShutDown(lang('file.typeNotSupport'));
        }
        $fileType = getFileType($info['ext']);
        $prefix = date('Ymd') . "/";
        $name = str_replace('.' . $info['ext'], '', $info['name']);
//        $file = FileModel::where(['md5' => $info['md5']])->find();
        $file = AttachmentModel::where(['sha1' => sha1($info['md5'])])->find();
        // 判断文件是否存在，如果有则不再上传
        if (empty($file)) {
//            $newName = sha1(uniqid()) . '.' . $info['ext'];
            $newName = sha1($info['md5']) . '.' . $info['ext'];
            $object = $prefix . $newName;
            Filesystem::disk($this->disk)->putFileAs($prefix, $filePath, $newName);
        } else {
            $object = substr($file['url'], 8);
        }
        // 把左边的/去掉再加上，避免有些有/有些没有
        $object = '/' . ltrim($object, '/');
        $ret = [
            "src" => $object,
            "name" => $name,
            "cate" => $fileType,
            "size" => $info['size'],
            "md5" => $info['md5'],
            "file_type" => $info['mime'],
            "ext" => $info['ext'],
            "type" => 2,
            'user_id' => $uid,
            'sha1' => empty($file['sha1']) ? '' : $file['sha1'],
        ];

        if ($message) {
            // 自动获取视频第一帧,视频并且是使用的阿里云
            if ($message['type'] == 'video') {
                if ($this->disk == 'aliyun') {
                    $message['extends']['poster'] = $this->url . $ret['src'] . '?x-oss-process=video/snapshot,t_1000,m_fast,w_800,f_png';
                } else {
                    $message['extends']['poster'] = 'https://im.file.raingad.com/static/image/video.png';
                }
            }
            // 如果发送的文件是图片、视频、音频则将消息类型改为对应的类型

            if ($message['type'] == 'image') {
                $extends = $this->getImageSizeInfo($info['path']);
                $message['extends'] = $extends;
            }
//            $newFile = new FileModel;
//            $newFile = new AttachmentModel();
//            // 录音就不保存了
//            if ($message['type'] != 'voice') {
//                $newFile->save($ret);
//            }

//            $message['content'] = $ret['src'];
//            $message['file_id'] = $newFile->file_id ?? 0;
//            $message['file_cate'] = $fileType;
//            $message['file_size'] = $info['size'];
//            $message['file_name'] = $name . '.' . $info['ext'];
//            $message['user_id'] = $uid;

//            $data = Message::sendMessage($message);
            return $data;
        } else {
            return $ret;
        }

    }

    // 上传一般文件
    public function uploadFile()
    {
        $param = $this->request->param();
        try {
            $file = request()->file('file');
            $info = $this->upload($param, $file);
            return success(lang('file.uploadOk'), $info);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }


    // 获取上传文件的信息
    protected function getFileInfo($file, $path, $isObj = false)
    {
        $info = [
            'path' => $file->getRealPath(),
            'size' => $file->getSize(),
            'mime' => $file->getMime(),
            'ext' => $file->extension(),
            'md5' => $file->md5(),
        ];
        if ($isObj) {
            $info['name'] = $file->getOriginalName();
        } else {
            // 根据路径获取文件名
            $pathInfo = pathinfo($path);
            $info['name'] = $pathInfo['basename'];
        }
        return $info;

    }


    // 普通上传头像
    public function uploadAvatar()
    {
        $param = request::param();
        try {
            $file = request()->file('file');
            $uid = request()->userInfo['user_id'];
            $info = $this->upload($param, $file, 'avatar/' . $uid . '/');
            User::where(['user_id' => $uid])->update(['avatar' => $info['src']]);
            $url = $this->url . $info['src'];
            return success(lang('file.uploadOk'), $url);
        } catch (\Exception $e) {
            return error($e->getMessage());
        }
    }

    // 服务器上传头像
    public function uploadLocalAvatar($file, $param, $uid)
    {
        try {
            $info = $this->upload($param, $file, 'avatar/' . $uid . '/', false);
            return $info['src'];
        } catch (\Exception $e) {
            return $e->getMessage() . $e->getLine();
        }
    }

    // 获取图片的尺寸
    protected function getImageSizeInfo($file)
    {
        $extends = [];
        // 如果图片获取图片的尺寸
        $imageSize = getimagesize($file);
        $extends['width'] = $imageSize[0];
        $extends['height'] = $imageSize[1];
        // 如果宽大于高则为横图，宽度填充模式，否则为竖图，高度填充模式
        if ($imageSize[0] >= $imageSize[1]) {
            $extends['fixMode'] = 1;  // 宽度填充
        } else {
            $extends['fixMode'] = 2;  // 高度填充
        }
        if ($imageSize[0] < 200 && $imageSize[1] < 240) {
            $extends['fixMode'] = 3;    // 小图
        }
        return $extends;
    }

}